package dao;

import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.List;

import entity.File;
import entity.User;
import util.DBHelp;
import util.RowMapper;

public class FileDao {

	private DBHelp<File> db=new DBHelp<File>();
	
	public void save(File file){
		String sql="insert into t_file (id,filename,pathname,filesize,createtime,filetype_id,user_id) values (?,?,?,?,?,?,?)";
		db.executeSQL(sql, file.getId(),file.getFilename(),file.getPathname(),file.getFilesize(),file.getCreatetime(),file.getFiletype_id(),file.getUser_id());
	}
	
	public List<File> findByTypeId(String id){
		String sql="SELECT t_file.id,filename,pathname,createtime,filesize,user_id,username ,filetype_id FROM t_file LEFT JOIN t_user ON t_user.id=user_id where filetype_id=? ";
		
		return db.executeQueryToList(sql,new RowMapper<File>(){
			public File mapRow(ResultSet rs) throws SQLException{
				File file=new File();
				file.setCreatetime(rs.getString("createtime"));
				file.setFilename(rs.getString("filename"));
				file.setFilesize(rs.getLong("filesize"));
				file.setFiletype_id(rs.getString("filetype_id"));
				file.setId(rs.getString("id"));
				file.setPathname(rs.getString("pathname"));
				file.setUser_id(rs.getString("user_id"));
				
				User user=new User();
				user.setId(rs.getString("user_id"));
				user.setUsername(rs.getString("username"));
				file.setUser(user);
				
				return file;
			}
			
		},id);
		
	}

	public File findById(String id) {
		String sql="SELECT id,NAME,createtime,user_id,project_id FROM t_filetype where id=?";
		return db.executeQueryToObject(sql, new FileRowMapper(), id);
	}
	public class FileRowMapper implements RowMapper<File>{

		public File mapRow(ResultSet rs) throws SQLException {
			File file=new File();
			file.setCreatetime(rs.getString("createtime"));
			file.setFilename(rs.getString("filename"));
			file.setFilesize(rs.getLong("filesize"));
			file.setFiletype_id(rs.getString("filetype_id"));
			file.setId(rs.getString("id"));
			file.setPathname(rs.getString("pathname"));
			file.setUser_id(rs.getString("user_id"));
		
			return file;
		}
	}
	public void delete(String id) {
		String sql="DELETE FROM t_file WHERE id=?";
		db.executeSQL(sql, id);
	}
	public File findByFileId(String id){
		String sql="SELECT id,filename,pathname,filesize,createtime,filetype_id FROM t_file where id=?";
		return db.executeQueryToObject(sql, new FileRowMapper(), id);
		
	}
}
